/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *fast = head, *slow = head;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow)
            {
                ListNode *meet = slow;
                while (meet != head)
                {
                    meet = meet->next; // 一个指针从相遇点走
                    head = head->next; // 一个指针从头走
                }
                return meet; // 会在入环的第一个节点相遇
            }
        }
        return nullptr;
    }
};